package jstudy.gu.kit.string;

import java.util.Collection;
import java.util.stream.Stream;

public final class Joiner {
	private final String delimiter;
	private final int delimiterLength;
	private StringBuilder value = new StringBuilder();
	private String nullValue;

	public Joiner(String delimiter) {
		this(delimiter, null);
	}

	/**
	 * @param delimiter
	 * @param nullValue : 如果添加的节点为null,则转为此值
	 */
	public Joiner(String delimiter, String nullValue) {
		if (delimiter == null) {
			delimiter = "";
		}
		this.delimiter = delimiter;
		this.delimiterLength = delimiter.length();
		this.nullValue = String.valueOf(nullValue);
	}

	@Override
	public String toString() {
		if (value.length() == 0) {
			return "";
		}
		return value.substring(delimiterLength);
	}

	public Joiner add(Object newElement) {
		return this.add(newElement == null ? nullValue : newElement.toString());
	}

	public Joiner add(String newElement) {
		if (newElement == null) {
			newElement = nullValue;
		}
		value.append(delimiter).append(newElement);
		return this;
	}

	public Joiner add(Collection<?> elements) {
		if (elements != null) {
			elements.forEach(this::add);
		}
		return this;
	}

	public Joiner add(Stream<?> stream) {
		if (stream != null) {
			stream.forEach(this::add);
		}
		return this;
	}

	public Joiner add(Object... elements) {
		for (Object obj : elements) {
			add(obj);
		}
		return this;
	}

	public int length() {
		int length = value.length();
		if (length != 0) {
			length = length - delimiterLength;
		}
		return length;
	}

	public boolean isEmpty() {
		return value.length() == 0;
	}

	public String subString(int start) {
		if (value.length() != 0) {
			start += delimiterLength;
		}
		return value.substring(start);
	}

	public String subString(int start, int end) {
		if (value.length() != 0) {
			start += delimiterLength;
			end += delimiterLength;
		}
		return value.substring(start, end);
	}

}
